package com.test.practice.io.objectstream;

import lombok.Cleanup;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
 * 随机存取文件流
 *
 * @Description: 随机存取文件流
 * =======================
 * @Author: Jovi
 * =======================
 * @Date: Created in 2023-02-10
 * =======================
 * @Version: 1.1.2.0
 */
public class RandomAccessDemo {

    public static void main(String[] args) throws Exception {
//        m1();

        m2();

    }

    /**
     * 指定位置覆盖
     * @throws IOException
     */
    private static void m2() throws IOException {
        @Cleanup RandomAccessFile dstFile = new RandomAccessFile("ttt1.txt", "rw");

        //指针从第几位开始覆盖，从0开始
        dstFile.seek(4);
        //覆盖数据
        dstFile.write("jovi".getBytes());
    }

    /**
     * 常规读写
     *
     * @throws IOException
     */
    private static void m1() throws IOException {
        @Cleanup RandomAccessFile srcFile = new RandomAccessFile("1.png", "r");
        @Cleanup RandomAccessFile dstFile = new RandomAccessFile("3.png", "rw");

        byte[] datas = new byte[1024];
        int len;
        while ((len = srcFile.read(datas)) != -1) {
            dstFile.write(datas, 0, len);
        }
    }
}
